package com.shareyi.wox.spring;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.shareyi.wox.config.WoxConstant;
import com.shareyi.simpleserver.servlet.ApplicationContext;
import com.shareyi.simpleserver.servlet.ServletContextListener;

public class WoxSpringServletContextListener
		implements ServletContextListener {
	
	
	private static Log log=LogFactory.getLog(ServletContextListener.class);
	private static final String CONTEXT_CONFIG_LOCATION = "contextConfigLocation";
	
	
	public void contextInitialized(ApplicationContext applicationContext) {
		String contextConfigLocation=(String) applicationContext.getParamValue(CONTEXT_CONFIG_LOCATION);
		if(StringUtils.isNotEmpty(contextConfigLocation)){
			try{
				String[] paths=resolvePath(contextConfigLocation);
				ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(paths);
				WoxSpringObjectFactory woxSpringObjectFactory=new WoxSpringObjectFactory(context);
				applicationContext.setParamValue(WoxConstant.WOX_ObjectFactory, woxSpringObjectFactory);
				log.info("Spring wox ServletContextListener haven been initaled ");
			}catch(Exception e){
				log.error("The wox spring bean factory bridge have not been initialed,it will use the default object factory");
			}
		}
	}

	public void contextDestroyed(ApplicationContext applicationContext) {
		log.info("application destoryed");
	}

	
	
	private String[] resolvePath(String path){
		path=path.trim();
		String[] paths=path.split(",");
		return paths;
		
	}
}
